(ns api-proxy.handler
  (:require [ring.util.response :as resp]
            [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]
            [clojure.pprint :refer [pprint]]
            [clj-http.client :as client]))

(defmacro ep [expr]
  `(let [v# ~expr] (println v#) v#))

(defn proxy-get [req]
  (try (let [{:keys [query-params]} req
         url (query-params "_")
         query-params (dissoc query-params "_")]
     (if url
       (let [{:keys [status headers body]}
             (client/get url {:query-params query-params
                                 :as :stream})]
         {:status status
          :headers headers
          :body body})
       (throw (Exception. "Incorrect url."))))
       (catch Exception e {:status 403
                           :body (.getMessage e)})))

(defroutes app-routes
  (GET "/" [] "A useful api proxy.")
  (GET "/get" [] proxy-get)
  ;; (POST "/proxy" [] proxy-handler)
  (route/not-found "Not Found"))

(def app
  (wrap-defaults #'app-routes site-defaults))
